<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools title="总记录数据total条">
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="lotOut"
          >excel导出</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </PageTools>
      </el-card>
    </div>
    <!-- // 表格 -->
    <el-card style="margin-top: 10px">
      <el-table
        border
        :data="emploadList"
        :default-sort="{ prop: 'workNumber' }"
      >
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像" prop="staffPhoto">
          <template slot-scope="scope">
            <ImageHolder :src="scope.row.staffPhoto">
            <!-- <img :src="scope.row.staffPhoto"> -->
              <!-- {{ formth(scope.row.formOfEmployment) }} -->
            </imageholder></template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template slot-scope="scope">
            <!-- <button @click="f({scope})">6</button> -->
            <!-- 第一种方法 -->
            <!-- {{ scope.row.formOfEmployment === 1 ? '正式' : '非正式' }} -->
            <!-- 第二种方法 -->
            <!-- {{ formth(scope.row.formOfEmployment) }} -->
            {{ formth(scope.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" sortable prop="correctionTime" />
        <!-- <el-table-column label="账户状态" prop="staffPhoto" /> -->
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="$router.push('/employees/detail/?id=' + scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
            <el-button
              type="text"
              size="small"
              @click="hDel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          background
          :total="total"
          :page-size="pageParams.size"
          :current-page="pageParams.page"
          :page-sizes="[3, 5, 10, 15, 20]"
          layout="sizes,prev,pager,next"
          @current-change="hCurrentChange"
          @size-change="hSizeChange"
        />
      </el-row>
    </el-card>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="新增员工"
      :visible.sync="showDialog"
    >
      <empDialog ref="empDialog" @success="hSuccess" @close="hClose" />

    </el-dialog>
    <el-dialog :visible.sync="showDialogRole"> <AssignRole v-if="showDialogRole" :cur-id="curId" @close="hCloseRoule" @success="hSuccessRoule" /></el-dialog>
  </div>
</template>

<script>

import { getEmployeeList, delEmployee } from '@/api/employees.js'
import empDialog from './empDialog.vue'
import { TYPE_MAP } from '@/contsant/index'
import AssignRole from './AssignRole.vue'
// import { login } from '@/api/user'
export default {
  components: {
    empDialog, AssignRole
  },
  data() {
    return {
      showDialog: false, // 弹窗
      showDialogRole: false, // 用户
      emploadList: [],
      pageParams: { page: 1, size: 3 },
      total: 0,
      curId: ''// 根据 id 保存
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 接收 子组件
    hSuccessRoule() {
      this.showDialogRole = false
    },
    // 点击 取消
    hCloseRoule() {
      this.showDialogRole = false
      // this.showDialog = false
    },
    // 点击 分配
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    formatData(rows) {
      const Eheader = Object.keys(rows[0])

      const mapObj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const header = Eheader.map(en => mapObj[en])
      const data = rows.map(obj => {
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
    async lotOut() {
      const res = await getEmployeeList(this.pageParams)
      const { header, data } = this.formatData(res.data.rows)
      console.log('员工信息', header, data)
      import('@/vendor/Export2Excel').then(excel => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)
        // 生成excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 删除操作
    async  doDel(id) {
      try {
        // 1.获取接口数据
        await delEmployee(id)
        // 2. 提示接口
        this.$message.success('删除成功')
        //
        if (this.emploadList.length === 1 && this.pageParams.page > 1) {
          this.pageParams.page--
        }
        // 3.重新 渲染
        this.loadEmployeeList()
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 点击了删除
    hDel(id) {
      this.$confirm('确定要删除吗', '提示').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // formth(type) {
    //   // console.log(d)
    //   if (type === 1) {
    //     return '正式'
    //   } else if (type === 2) {
    //     return '非正式'
    //   }
    // },
    formth(type) {
      return TYPE_MAP[type] || '未知'
    },
    async  loadEmployeeList() {
      const res = await getEmployeeList(this.pageParams)
      console.log('res', res)
      // 保存
      this.emploadList = res.data.rows
      this.total = res.data.total
    },
    hSizeChange(curPageNum) {
      console.log(curPageNum)
      this.pageParams.size = curPageNum
      // 每次 点击 都跳转到 第一页
      this.pageParams.page = 1
      // 重新 渲染
      this.loadEmployeeList()
    },
    // 点击的页码
    hCurrentChange(curPage) {
      console.log(curPage)
      this.pageParams.page = curPage
      // 数据更新
      this.loadEmployeeList()
    },
    // 点击取消关闭弹窗
    hClose() {
      this.showDialog = false
      this.$refs.empDialog.resetForm()
    },
    // 添加成功
    hSuccess() {
      // 数据更新
      this.loadEmployeeList()
      // 关闭窗口
      this.showDialog = false
      this.total++
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)
    }

    // return (this.pageParams.page -1) * this.pageParams.size + index +1
  }
}
</script>
